package org.agile.grenoble.client;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.agile.grenoble.data.xml.QuestionsReader;
import org.agile.grenoble.questions.QuestionsDocument;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class GetQuestionsClient {
	
	
public static QuestionsDocument GetQuestionsClient() {
		
		Client c = Client.create();
		c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
		System.out.println("Client created, going to create a webresource") ;
		StringBuffer url =  new StringBuffer("http://localhost:9998/");
		
		WebResource r = c.resource(url.toString());
		MultivaluedMap<String, String> params = new MultivaluedMapImpl();
		params.add("getNumber","false");
		params.add("all", "true");
		
		WebResource resource = r.path("questions").queryParams(params);

		System.out.println("WebResource created, getting the answer");
		Builder builder = resource.accept(MediaType.APPLICATION_JSON_TYPE,MediaType.TEXT_XML_TYPE) ;
		Builder b1 = builder.header("X-FOO", "BAR");
		String response = b1.get(String.class);
		
		//System.out.println("Response is :" + response ) ;
		QuestionsDocument questions = null ; 
		try {
			questions = QuestionsReader.getDocumentFromString(response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return questions;
	}
}
